package com.ojoin.ojoin.eb_spider.service.catchdata;

import com.ojoin.ojoin.eb_spider.bean.CiMingPersonGroup;
import com.ojoin.ojoin.eb_spider.bean.CiMingUserOrder;
import com.ojoin.ojoin.eb_spider.dao.SysNotifyLogMapper;
import com.ojoin.ojoin.eb_spider.model.SysNotifyLog;
import com.ojoin.ojoin.eb_spider.service.QueueSenderServie;
import com.ojoin.ojoin.eb_spider.service.QueueService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.WebDriveBaseServiceImpl;
import com.ojoin.ojoin.eb_spider.utils.Config;
import com.ojoin.ojoin.eb_spider.utils.HttpUtils;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataStartMessage;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CiMingAppointmentServiceImpl extends WebDriveBaseServiceImpl {

    /**
     * 线程内共享Connection，ThreadLocal通常是全局的，支持泛型
     */
    @Autowired
    @Qualifier("CiMingQueue")
    private QueueService<CiMingUserOrder> queueService;

    @Autowired
    private QueueSenderServie queueSenderServie;

    @Autowired
    @Qualifier("queue_crawler_res")
    private Destination destination;

    @Autowired
    private SysNotifyLogMapper sysNotifyLogMapper;

    private static Object object = new Object();

    private static CiMingPersonGroup cpg ;

    private static Logger log = LoggerFactory.getLogger(CiMingAppointmentServiceImpl.class);

    private static String loginUrl = "http://book.code.ciming.com/bookClient2.0/customerInfo.html";

    private static final int DRIVE_SIZE = 1;

    @Override
    public boolean LoginByUserInfo(String baseUrl, String username, String password) throws Exception {
        // 开始登陆
        //try {
        this.getWebDriver().get("http://book.code.ciming.com/bookClient2.0/byEeCode_login.html");

        this.getWebDriver().sendKeys("id", "orderCode", username);

        WebElement verifyE = this.getWebDriver().findElement(WebDriverService.ID,
                "createCheckCode");
        String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);

        this.getWebDriver().sendKeys(WebDriverService.ID, "VCode",
                code.toLowerCase());

        this.getWebDriver().sendKeys("id", "orderPassword", password);

        this.getWebDriver().click(WebDriverService.xpath, "/html/body/div[2]/div/div[2]/div/a");

		/*} catch (Exception e) {
                        log.error(" ", e);

		}*/

        return this.getWebDriver().getDriver().getCurrentUrl().startsWith(loginUrl);
    }

    public boolean ready(String username) throws Exception {
        prepareCatchData(CatchDataStartMessage.LOCALHOST, Config.CIMING, username);
        return true;
    }

    public boolean isReady() throws Exception {
        return null != this.getWebDriver().getDriver();
    }

    public boolean isLogin() throws Exception {
        this.getWebDriver().get(loginUrl);

        // 因为有跳转，所以根据页面中元素判断
        return this.getWebDriver().IsExist(WebDriverService.ID, "card");
    }

    @Override
    public void init() {
        super.init();
        try {
            String json =  HttpUtils.get("http://bj-bdy-public.oss-cn-beijing.aliyuncs.com/dev/reptile/json/ciMing/personGroup.js");

            if(!StringUtils.isEmpty(json)){
                json = json.substring(json.indexOf("{"));
                cpg = JSONUtils.parseObject(json,CiMingPersonGroup.class);
            }

        } catch (IOException e) {
           LogUtils.error(log,e);
        }

        if(null == cpg){
            cpg = new CiMingPersonGroup();
        }

    }

    public synchronized boolean login(String username, String password) throws Exception {
        int loginCount = 1;
        boolean ready = isReady();
        if (!ready) {
            init();
            ready = ready(username);
        }

        if (ready) {
            boolean flag = isLogin();

            if (!flag) {
                while (loginCount < verifycodeRetryCount) {
                    flag = LoginByUserInfo("", username, password);
                    if (flag) {
                        return flag;
                    }
                }
            } else {
                LogUtils.info(log, "username" + username + "on line");
            }

        }

        return false;
    }

    public synchronized void deal() throws Exception {
        while (!queueService.isEmpt()) {
            CiMingUserOrder co = queueService.consume();
            deal(co);
        }
    }

    public synchronized void deal(Object object) throws Exception {
        SysNotifyLog record = new SysNotifyLog();
        try {
            if (object instanceof CiMingUserOrder) {
                CiMingUserOrder tjUserOrder = (CiMingUserOrder) object;
                String messageid = Config.CM_PREPARE+"_"+tjUserOrder.getUserOrder().getId();
                SysNotifyLog dbrecord = sysNotifyLogMapper.selectByMessageId(messageid);

                record.setId(dbrecord.getId());

                if (isLogin()) {

                    boolean search = search(tjUserOrder);
                    boolean healthyMessage = false;
                    boolean locateTime = false;
                    if (search) {
                        healthyMessage = healthyMessage(tjUserOrder);
                    }

                    if (healthyMessage) {
                        locateTime = locateTime(tjUserOrder);
                    }

                    if (locateTime) {
                        record.setStatus(Config.SUCCESS);
                    } else {
                        record.setStatus(Config.FAIL);
                    }
                } else {
                    throw new BusinessException("预约平台不在线");
                }
            }
        } catch (Exception e) {
            record.setStatus(Config.FAIL);
            if(null != e.getMessage()){
                record.setCause(e.getMessage().substring(0,(e.getMessage().length()>200)?200:e.getMessage().length()));
            }
        } finally {
            sysNotifyLogMapper.updateByPrimaryKeySelective(record);
            queueSenderServie.send(destination,record);
        }


    }

    @Override
    public void repairDeal(Object object) throws Exception {
        if (object instanceof CiMingUserOrder) {
            CiMingUserOrder tjUserOrder = (CiMingUserOrder) object;
            String messageid = Config.CM_PREPARE+"_"+tjUserOrder.getUserOrder().getId();

            SysNotifyLog record = sysNotifyLogMapper.selectByMessageId(messageid);

            if(null == record){
                queueService.produce(tjUserOrder);
                record = new SysNotifyLog();
                record.setChannel(Config.CM_PREPARE);
                record.setContent(JSONUtils.toJSONString(object));
                record.setMessageid(messageid);
                record.setStatus(Config.ONREADY);
                record.setCt(new Date());
                sysNotifyLogMapper.insert(record);

            }


        }
    }

    /**
     * 身份证验证
     */

    public boolean search(CiMingUserOrder tjUserOrder) {
        // 设置订单信息
        // 证件
        boolean fid = false;
        WebElement span = this.getWebDriver().findElement(WebDriverService.ID, "card");
        List<WebElement> spans = this.getWebDriver().findElements(span, WebDriverService.CSS, "span");
        for (WebElement sp : spans) {
            if (sp.getText().equals(tjUserOrder.getIdcardtype())) {
                sp.click();
                fid = true;
                break;
            }
        }
        this.getWebDriver().sendKeys(WebDriverService.ID, "idcard", tjUserOrder.getUserOrder().getIdcard());


        // 婚否
        if (tjUserOrder.getUserOrder().getIsMarried()) {
            this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"customerForm\"]/ul[1]/li[3]/p[1]/span[1]");
        }

        //人种
        //this.getWebDriver().click(WebDriverService.ID, "ethnicid");
        // this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"ethnicid\"]/option[2]");

        WebElement sex =this.getWebDriver().findElement(WebDriverService.xpath,"//*[@id=\"customerForm\"]/ul[1]/li[3]/p[2]/span[1]");
        if(sex.getAttribute("class").equals("cur")){
            tjUserOrder.getUserOrder().setSex((byte) 1);
        }

        this.getWebDriver().sendKeys(WebDriverService.ID, "name", tjUserOrder.getUserOrder().getName());
        this.getWebDriver().sendKeys(WebDriverService.ID, "mobilephone", tjUserOrder.getUserOrder().getMobile());

        // 下一步
        this.getWebDriver().click(WebDriverService.xpath, "/html/body/div[2]/div[2]/a[2]");
        // 个人资料不填，直接下一步
        this.getWebDriver().click(WebDriverService.xpath, "/html/body/div[2]/div[3]/a[2]");

        return fid;
    }

    public boolean healthyMessage(CiMingUserOrder tjUserOrder) throws IOException {
        boolean fpg = false;
        //try {


            this.getWebDriver().waitVisibilityOfElementLocated(WebDriverService.ID, "personGroup");

            this.getWebDriver().click(WebDriverService.ID, "personGroup");
            // 选中具体套餐
            List<WebElement> options = this.getWebDriver().findElements(WebDriverService.CSS, "#personGroup > option");

            String personGroup = tjUserOrder.getUserOrder().getGroupId();

            // 如果需要更新

            if(needUpdatePersonGroup(tjUserOrder.getKey()) && StringUtils.isEmpty(personGroup)){
                Map map = new HashMap();
                for (WebElement option : options) {
                    String key = option.getAttribute("value");
                    String rext = option.getText();
                    map.put(key,rext);
                }

                cpg.getType().put(tjUserOrder.getKey(),map);
                cpg.getUt().put(tjUserOrder.getKey(),TimeUtils.getCurDate());

                Map<String,String> ma = new HashMap<>();



                String js = "var personalGroupDate ="+JSONUtils.toJSONString(cpg);

                ma.put("json",js);
                ma.put("name","personGroup.js");
                HttpUtils.post("http://localhost:8083/xmppUpload/upJson/reptile/json/ciMing",ma);

                return false;

            }


            for (WebElement option : options) {
                if (option.getAttribute("value").equals(personGroup)) {
                    option.click();
                    fpg = true;
                    break;
                }
            }

            this.getWebDriver().waitVisibilityOfElementLocated(WebDriverService.ID, personGroup);

            this.getWebDriver().click(WebDriverService.ID, personGroup);

            // 下一步
            WebElement next = this.getWebDriver().findElement(WebDriverService.CSS, "body > div.book_con > div.t-public-btn > a:nth-child(2)");
            this.getWebDriver().clickByJS(next);

            // 确定
            this.getWebDriver().click(WebDriverService.ID, "sureButton");
       /* } catch (Exception e) {
            LogUtils.error(log, e);
        }*/
        return fpg;
    }

    public boolean needUpdatePersonGroup(String key){
        if(null != cpg.getType() ){
              // 说明有值 判断时间
            if(TimeUtils.getCurDate().equals(cpg.getUt().get(key))){
               return false;
            }
        }else {
            Map<String, Map<String, String>> mp = new HashMap<>();
            Map<String, String> ut = new HashMap<>();

            cpg.setType(mp);
            cpg.setUt(ut);
        }

        return true;
    }



    public boolean locateTime(CiMingUserOrder tjUserOrder) {
        // 获取分院
        boolean flocate = false;
        boolean ftime = false;
        String locate = tjUserOrder.getUserOrder().getFrontName();
        WebElement div = this.getWebDriver().findElement(WebDriverService.xpath, "/html/body/div[2]/div[2]/div/div[1]");
        List<WebElement> ps = this.getWebDriver().findElements(div, WebDriverService.CSS, "p");
        for (WebElement p : ps) {
            WebElement span = this.getWebDriver().findElement(p, WebDriverService.CSS, "span");
            if (span.getText().equals(locate)) {
                span.click();
                flocate = true;
                break;
            }
        }

        // 时间预约
        int orderTime = tjUserOrder.getUserOrder().getOrdertime().getDate();
        WebElement table = this.getWebDriver().findElement(WebDriverService.ID, "calendar");
        List<WebElement> trs = this.getWebDriver().findElements(table, WebDriverService.CSS, "tr");
        for (int i = 2; i < trs.size(); i++) {
            List<WebElement> tds = this.getWebDriver().findElements(trs.get(i), WebDriverService.CSS, "td");
            for (WebElement td : tds) {
                if (td.getText().equals(orderTime + "")) {
                    td.click();
                    ftime = true;
                    break;
                }
            }

            if (ftime) {
                break;
            }
        }


        // 提交预约

        this.getWebDriver().click(WebDriverService.xpath, "/html/body/div[2]/div[3]/a[2]");

        // 确定

        //this.getWebDriver().click(WebDriverService.xpath," //*[@id=\"payType0\"]/a");

        return flocate && ftime;
    }
}
